#include <elf.h>
#include "ff.h"
#include "kernel/astralapi.h"

typedef struct elfloader
{
    Elf32_Phdr prog[0];
} progtable;


/**
 * @brief This function read program load segment into memory
 * 
 * @param fp 
 * @param phd 
 * @return int 
 */
int program_load(FIL *fp, Elf32_Phdr *phd)
{
    int read = 0;
    if (phd->p_type == PT_LOAD)
    {
        kprint("%x %d %d\n", phd->p_vaddr, phd->p_filesz, phd->p_memsz);
    }
    return 0;
}

int load_elf(const char *name)
{
    FIL fp;
    UINT br;
    Elf32_Ehdr head;
    kprint("loading elf %s\n", name);
    f_open(&fp, name, FA_READ);
    f_read(&fp, &head, sizeof(head), &br);
    kprint("%s total %d segments\n",head.e_ident, head.e_phnum);
    f_lseek(&fp, head.e_phoff);
    progtable *prog = ff_alloc(sizeof(Elf32_Phdr) * head.e_phnum);
    f_read(&fp, prog, sizeof(Elf32_Phdr) * head.e_phnum, &br);
    kprint("phentsize: %d\n", head.e_phentsize);

    for (int i = 0; i < head.e_phnum; i++)
    {
        program_load(&fp, &prog->prog[i]);
    }
    f_close(&fp);
}

void exec(int argc, char *argv[])
{
    char *name = argv[1];
    load_elf(name);
}
